import sys
import threading
from time import sleep
import functions
from functions import logs
from functions import toml2
from functions import api
from functions import run_frp
from functions import sql




def frpcommand2(runcommand2):
    functions.run_frp.frpcommand(command=runcommand2)

def frpreset(resetcommand2,enable=2):
    functions.run_frp.reset(command=resetcommand2, enable=enable)

def main():
    try:
        print('''
       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
     @@                                                           @@
    @  &&&             &&&                                          @
    @  &&&&           &&&&                                          @
    @  && &&         && &&                                          @
    @  &&  &&       &&  &&      &&&&&&       &&&&&&     &&&&&&&&&&  @
    @  &&   &&     &&   &&    &&      &&   &&      &&   &&      &&  @
    @  &&    &&   &&    &&    &&      &&   &&      &&   &&      &&  @
    @  &&     && &&     &&    &&      &&   &&      &&   &&      &&  @
    @  &&      &&&      &&      &&&&&&       &&&&&&     &&      &&  @
    @  -----------------------------------------------------------  @
    @    &&&&&&&                                                    @
    @   &&     &&                                                   @
    @  &&                                                           @
    @  &&                                                           @
    @   &&&&&&&&&     &&    &&&    &&      &&&&&& &&   &&&&&&&&     @
    @           &&    &&   && &&   &&    &&      &&&   &&      &&   @
    @            &&   &&  &&   &&  &&   &&        &&   &&       &&  @
    @            &&   && &&     && &&   &&        &&   &&       &&  @
    @  &&       &&    &&&&       &&&&    &&      &&&   &&      &&   @
    @   &&&&&&&&      &&&         &&&      &&&&&& &&   &&&&&&&&     @
    @                                                  &&           @
    @                                                  &&           @   &       &       &&        &&
    @                                                  &&           @    &     &       & &       & &
    @                                                  &&           @     &   &          &         &
     @@                                                           @@       & &           &         &
       @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@          &          &&&&&  &  &&&&& 
       ''')
        log.log_info("SwapMoon断网恢复程序正在启动")
        sleep(0.02)
        while True:
            threads = []#存储线程对象
            while True:
                if functions.toml2.readconfig()['values'][0]['enabled'] == 'T':
                    log.log_info("FRP自启动已开启")
                    sleep(0.01)
                    break
                elif functions.toml2.readconfig()['values'][0]['enabled'] == 'F':
                    log.log_info("FRP自启动已关闭")
                    sleep(0.01)
                else:
                    log.log_warning("config.toml的enabled参数错误，已默认关闭FRP自启动")
                    sleep(0.01)
                frpenable1 = input('\n【y】启动FRPC\n【n】重置FRPC初始配置\n输入^c关闭程序(y/n):')
                if frpenable1 == 'y':
                    break
                elif frpenable1 == 'n':
                    data1 = functions.toml2.readconfig()
                    data2 = data1['frpcdata'][0]['frp_path']
                    filenames = data1['values'][0]['frptomllist']
                    functions.toml2.deltoml(path=data2 + '/proxy/', filenames=filenames)
                    functions.sql.resetsql()
                    functions.toml2.numup(0)
                    functions.toml2.frptomllist_reset()
                    functions.toml2.useremoteport_up(remoteport=[])
                    functions.toml2.enabled_reset()


            log.log_info("正在请求映射表数据")
            json_data = functions.api.getapidata()
            sleep(0.01)

            log.log_warning("正在重置数据库")
            functions.sql.resetsql()
            sleep(0.01)

            log.log_info("正在写入数据库")
            for i in json_data['Data']['data']:
                functions.sql.writein(i)
            sleep(0.01)

            log.log_info("正在写入配置文件")
            #从数据库获取打开状态的映射记录数据
            sql_data0 = functions.sql.readsql()  # 数据库映射列表数据
            sql_data = []
            for sqldata in sql_data0:
                if sqldata[7] == 'yes':
                    sql_data.append(sqldata)
                else:
                    continue
            functions.toml2.write_in_all(sql_data=sql_data)#创建所有子配置文件
            sleep(0.01)

            log.log_info("正在启动FRP")
            config_data = functions.toml2.readconfig()
            runcommand2 = config_data['frpcdata'][0]['frp_path']+'/frpc -c '+ config_data['frpcdata'][0]['includes'][0]
            runfrp = threading.Thread(target=frpcommand2,args=(runcommand2,))
            threads.append(runfrp)
            threads[0].start()
            sleep(0.01)

            log.log_info("正在启动控制台")
            log.log_info("控制台启动成功")

            while True:
                sleep(1)
                user_input = input('''
    +===================================+
    | 1 |        查询映射数据表         |
    +===================================+
    | 2 |           热重载FRP           |
    +===================================+
    | 3 |        输入并执行命令         |
    +===================================+
    | 4 |        关闭所有FRP项目        |
    +===================================+
    | 5 |        启动所有FRP项目        |
    +===================================+
    | 6 |       退出FRP并重置程序       |
    +===================================+
    | 7 |      修改某项穿透记录状态     |
    +===================================+
    | 8 |        重置程序并关闭         |
    +===================================+
    请输入代号以启用功能
    Or enter ^C to exit:''')

                if user_input == '1':#查询映射数据表
                    functions.sql.printout()
                    continue

                elif user_input == '2':#热重载FRP
                    log.log_info("正在热重载")
                    resetcommand1 = functions.toml2.readconfig()
                    resetcommand2 = resetcommand1['frpcdata'][0]['frp_path']+'/frpc reload -c '+ resetcommand1['frpcdata'][0]['includes'][0]
                    threads =[]
                    frpreset1 = threading.Thread(target=frpreset,args=(resetcommand2,))
                    threads.append(frpreset1)
                    threads[0].start()
                    continue

                elif user_input == '3':#输入并执行命令
                    command = input('   请输入终端命令：')
                    log.log_info("正在终端执行命令...")
                    functions.run_frp.frpcommand(command=command)
                    continue

                elif user_input == '4' or user_input == '5':
                    if user_input == '4':
                        enable = 0
                        log.log_info("正在关闭所有FRP项目")
                        functions.sql.change_enabled(enable='no')
                        data1 = functions.toml2.readconfig()
                        data2 = data1['frpcdata'][0]['frp_path']
                        filenames = data1['values'][0]['frptomllist']
                        functions.toml2.deltoml(path=data2 + '/proxy/', filenames=filenames)
                        resetcommand1 = functions.toml2.readconfig()
                        resetcommand2 = resetcommand1['frpcdata'][0]['frp_path'] + '/frpc reload -c ' + resetcommand1['frpcdata'][0]['includes'][0]
                        threads = []
                        frpreset1 = threading.Thread(target=frpreset, args=(resetcommand2,enable,))
                        threads.append(frpreset1)
                        threads[0].start()

                    else:
                        enable = 1
                        log.log_info("正在启动所有FRP项目")
                        functions.sql.change_enabled(enable='yes')
                        sql_data = functions.sql.readsql()  # 数据库映射列表数据
                        functions.toml2.write_in_all(sql_data=sql_data)  # 创建所有子配置文件
                        resetcommand1 = functions.toml2.readconfig()
                        resetcommand2 = resetcommand1['frpcdata'][0]['frp_path'] + '/frpc reload -c ' + resetcommand1['frpcdata'][0]['includes'][0]
                        threads = []
                        frpreset1 = threading.Thread(target=frpreset, args=(resetcommand2,enable,))
                        threads.append(frpreset1)
                        threads[0].start()
                    continue

                elif user_input == '6':#退出FRP并重置程序
                    log.log_warning("正在退出FRP并重置")
                    sleep(0.02)
                    data1 = functions.toml2.readconfig()
                    data2 = data1['frpcdata'][0]['frp_path']
                    command = data2+'/frpc stop -c '+data2+'/frpc.toml'
                    filenames = data1['values'][0]['frptomllist']
                    resetfrp = threading.Thread(target=frpcommand2, args=(command,))
                    threads = []
                    threads.append(resetfrp)
                    threads[0].start()
                    sleep(1)
                    functions.toml2.deltoml(path=data2 + '/proxy/', filenames=filenames)
                    functions.sql.resetsql()
                    functions.toml2.numup(0)
                    functions.toml2.frptomllist_reset()
                    functions.toml2.useremoteport_up(remoteport=[])
                    functions.toml2.enabled_reset()
                    break

                elif user_input == '7':#修改单条记录状态
                    while True:
                        flag = False
                        user_input2 = input('   请输入待修改穿透记录的ID(一次输入限1条)\n    (返回上级输入q)：')
                        sql_data = functions.sql.readsql()
                        if user_input2 == 'q':
                            break
                        for i in sql_data:
                            if i[0] == int(user_input2):
                                flag = True
                                break
                            else:
                                continue
                        if flag:
                            user_input3 = input(f'''
    +===================================+
    | 1 |            关闭穿透记录{user_input2}    |
    +===================================+
    | 2 |            开启穿透记录{user_input2}    |
    +===================================+
    (返回上级输入q)请输入:''')
                            if user_input3 == 'q':
                                continue

                            log.log_info(f"正在修改穿透记录{user_input2}的状态")
                            path = functions.toml2.readconfig()['frpcdata'][0]['frp_path'] + '/proxy/'
                            filenames = functions.toml2.readconfig()['values'][0]['frptomllist']
                            filenames2 = []
                            filename2 = []
                            for filename in filenames:
                                idcode = filename[filename.find('S')+1:filename.find('-')]
                                if idcode == user_input2:
                                    filename2.append(filename)
                                    continue
                                else:
                                    filenames2.append(filename)
                            sql_data = functions.sql.readsql()
                            for sqldata in sql_data:
                                if sqldata[0] == int(user_input2):
                                    finaldata = sqldata
                            if user_input3 == '1':
                                functions.sql.change_one_enabled(enable='no', id=int(user_input2))

                                log.log_info(f"正在删除穿透记录{user_input2}的配置文件")
                                functions.toml2.deltoml(path=path, filenames=filename2)
                                resetcommand1 = functions.toml2.readconfig()
                                resetcommand2 = resetcommand1['frpcdata'][0]['frp_path'] + '/frpc reload -c ' + \
                                                resetcommand1['frpcdata'][0]['includes'][0]
                                threads = []
                                frpreset1 = threading.Thread(target=frpreset, args=(resetcommand2,))
                                threads.append(frpreset1)
                                threads[0].start()
                                config_data = functions.toml2.readconfig()
                                config_data['values'][0]['frptomllist'] = filenames2
                                functions.toml2.dumptoml(dst_file='./lib/config.toml', data=config_data)
                                break

                            elif user_input3 == '2':
                                functions.sql.change_one_enabled(enable='yes', id=(user_input2))
                                sql_data = functions.sql.readsql()
                                for sqldata in sql_data:
                                    if sqldata[0] == int(user_input2):
                                        finaldata = sqldata

                                log.log_info(f"正在创建穿透记录{user_input2}的配置文件")
                                functions.toml2.open_one(sql_data=finaldata)
                                resetcommand1 = functions.toml2.readconfig()
                                resetcommand2 = resetcommand1['frpcdata'][0]['frp_path'] + '/frpc reload -c ' + \
                                                resetcommand1['frpcdata'][0]['includes'][0]
                                threads = []
                                frpreset1 = threading.Thread(target=frpreset, args=(resetcommand2,))
                                threads.append(frpreset1)
                                threads[0].start()
                                break
                            else:
                                log.log_error("菜单项不存在，请重新输入")
                        else:
                            log.log_info(f"查询到ID{user_input2}不存在，请核对后重试")


                elif user_input == '8':#重置程序并退出
                    log.log_warning("正在重置程序")
                    data1 = functions.toml2.readconfig()
                    data2 = data1['frpcdata'][0]['frp_path']
                    command = data2 + '/frpc stop -c ' + data2 + '/frpc.toml'
                    filenames = data1['values'][0]['frptomllist']
                    resetfrp = threading.Thread(target=frpcommand2, args=(command,))
                    threads = []
                    threads.append(resetfrp)
                    threads[0].start()
                    sleep(1)
                    functions.toml2.deltoml(path=data2 + '/proxy/', filenames=filenames)
                    functions.sql.resetsql()
                    functions.toml2.numup(0)
                    functions.toml2.frptomllist_reset()
                    functions.toml2.useremoteport_up(remoteport=[])
                    functions.toml2.enabled_reset()
                    log.log_info("正在退出程序")
                    sleep(0.03)
                    sys.exit()
                else:
                    log.log_error("菜单项不存在，请重新输入")


    except Exception as e:
        log.log_error(f"主程序出现异常:{e}")

if __name__ == '__main__':
    #创建一个Logger对象
    log = logs.Logger()
    main()
